package org.jeecg.modules.purchase.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.modules.purchase.mapper.PurchaseStockOutGoodsMapper;
import org.jeecg.modules.purchase.mapper.PurchaseStockOutMapper;
import org.jeecg.modules.purchase.service.IPurchaseStockService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.purchase.entity.PurchaseStockOutGoods;
import org.jeecg.modules.purchase.entity.PurchaseStockOut;
import org.jeecg.modules.purchase.vo.PurchaseStockOutPage;
import org.jeecg.modules.purchase.service.IPurchaseStockOutService;
import org.jeecg.modules.purchase.service.IPurchaseStockOutGoodsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 出库记录
 * @Author: jeecg-boot
 * @Date:   2022-11-15
 * @Version: V1.0
 */
@Api(tags="出库记录")
@RestController
@RequestMapping("/purchase/purchaseStockOut")
@Slf4j
public class PurchaseStockOutController {
	@Autowired
	private IPurchaseStockOutService purchaseStockOutService;
	@Autowired
	private IPurchaseStockOutGoodsService purchaseStockOutGoodsService;

	 @Resource
	 private IPurchaseStockService purchaseStockService;

	 @Autowired
	 private ISysBaseAPI iSysBaseAPI;

	 @Autowired
	 private PurchaseStockOutMapper purchaseStockOutMapper;

	 @Resource
	 private PurchaseStockOutGoodsMapper purchaseStockOutGoodsMapper;

	 /**
	  * 分页列表查询
	  *
	  * @param purchaseStockOut
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 @ApiOperation(value = "", notes = "出库记录-分页列表查询")
	 @GetMapping(value = "/list")
	 @PermissionData(pageComponent = "purchase/PurchaseStockOutList")
	 public Result<IPage<PurchaseStockOut>> queryPageList1(PurchaseStockOut purchaseStockOut,
														   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
														   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
														   HttpServletRequest req) {
		 String goodsName = null;
		if(purchaseStockOut.getGoodsName() != null && purchaseStockOut.getGoodsName().length()>0)
		{
			goodsName = purchaseStockOut.getGoodsName();
			purchaseStockOut.setGoodsName(null);
		}
		QueryWrapper<PurchaseStockOut> queryWrapper = QueryGenerator.initQueryWrapper(purchaseStockOut, req.getParameterMap());
		 Page<PurchaseStockOut> page = new Page<>(pageNo, pageSize);
		 IPage<PurchaseStockOut> pageList = null;
		 pageList = purchaseStockOutService.page(page , queryWrapper);
		 if(StringUtils.isNotEmpty(goodsName) && goodsName.length() > 0)
		  {
			queryWrapper.like("b.goods_name",goodsName);
			queryWrapper.eq("a.del_flag",0);
			queryWrapper.eq("b.del_flag",0);
			queryWrapper.apply("a.id = b.stock_out_id");
			pageList= purchaseStockOutService.pageList(page , queryWrapper);
		  }
//		 System.out.println(pageList);
		 return Result.OK(pageList);
		 //初始化出库物品子表
//		 List<PurchaseStockOut> purchaseStockOutList = pageList.getRecords();
//		 for (PurchaseStockOut stockOut : purchaseStockOutList) {
//			    String id = stockOut.getId();
//				String code = stockOut.getRepositoryCode();
//				String name = stockOut.getRepositoryName();
//			 LambdaQueryWrapper<PurchaseStockOutGoods> queryWrapper1 = new LambdaQueryWrapper<>();
//			 queryWrapper1.eq(PurchaseStockOutGoods::getStockOutId,id);
//			 List<PurchaseStockOutGoods> purchaseStockOutGoodsList = purchaseStockOutGoodsService.list(queryWrapper1);
//			 for (PurchaseStockOutGoods purchaseStockOutGoods : purchaseStockOutGoodsList) {
//				 if(StringUtils.isNotEmpty(code) && code.length()>0)
//				 {
//					 purchaseStockOutGoods.setCode(code);
//					 purchaseStockOutGoods.setName(name);
//					 purchaseStockOutGoodsService.updateById(purchaseStockOutGoods);
//				 }
//			 }
//		 }


//		 String goodsName = purchaseStockOut.getGoodsName();
//		 if(StringUtils.isNotEmpty(goodsName) && goodsName.length() > 0){
//			 List<PurchaseStockOut> resultList = new ArrayList<>();
//			 List<PurchaseStockOut> records = pageList.getRecords();
//			 for (PurchaseStockOut stock : records) {
//				 Integer byStockIds = getCountByStockIdAndName(stock.getId(), goodsName);
//				 if (byStockIds > 0) {
//					 resultList.add(stock);
//				 }
//			 }
//			 pageList.setTotal(resultList.size());
//			 pageList.setRecords(resultList);
//			 pageList.setCurrent(pageNo);
//			 pageList.setSize(pageSize);
//		 }

	 }

	 //@AutoLog(value = "出库记录-分页列表查询")
//	@ApiOperation(value="出库记录-分页列表查询", notes="出库记录-分页列表查询")
//	@GetMapping(value = "/list")
//	@PermissionData(pageComponent = "purchase/PurchaseStockOutList")
//	public Result<IPage<PurchaseStockOut>> queryPageList(PurchaseStockOut purchaseStockOut,
//								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
//								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
//								   HttpServletRequest req) {
//		QueryWrapper<PurchaseStockOut> queryWrapper = QueryGenerator.initQueryWrapper(purchaseStockOut, req.getParameterMap());
//		Page<PurchaseStockOut> page = new Page<PurchaseStockOut>(pageNo, pageSize);
//		IPage<PurchaseStockOut> pageList = purchaseStockOutService.page(page, queryWrapper);
//		return Result.OK(pageList);
//	}


	 /**
	 *   添加
	 *
	 * @param purchaseStockOutPage
	 * @return
	 */
	@AutoLog(value = "出库记录-添加")
	@ApiOperation(value="出库记录-添加", notes="出库记录-添加")
    //@RequiresPermissions("org.jeecg.modules:purchase_stock_out:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody PurchaseStockOutPage purchaseStockOutPage) {
		PurchaseStockOut purchaseStockOut = new PurchaseStockOut();
		BeanUtils.copyProperties(purchaseStockOutPage, purchaseStockOut);
		purchaseStockOutService.saveMain(purchaseStockOut, purchaseStockOutPage.getPurchaseStockOutGoodsList());
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param purchaseStockOutPage
	 * @return
	 */
	@AutoLog(value = "出库记录-编辑")
	@ApiOperation(value="出库记录-编辑", notes="出库记录-编辑")
    //@RequiresPermissions("org.jeecg.modules:purchase_stock_out:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody PurchaseStockOutPage purchaseStockOutPage) {
		PurchaseStockOut purchaseStockOut = new PurchaseStockOut();
		BeanUtils.copyProperties(purchaseStockOutPage, purchaseStockOut);
		PurchaseStockOut purchaseStockOutEntity = purchaseStockOutService.getById(purchaseStockOut.getId());
		if(purchaseStockOutEntity==null) {
			return Result.error("未找到对应数据");
		}
		purchaseStockOutService.updateMain(purchaseStockOut, purchaseStockOutPage.getPurchaseStockOutGoodsList());
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "出库记录-通过id删除")
	@ApiOperation(value="出库记录-通过id删除", notes="出库记录-通过id删除")
    //@RequiresPermissions("org.jeecg.modules:purchase_stock_out:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		purchaseStockOutService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "出库记录-批量删除")
	@ApiOperation(value="出库记录-批量删除", notes="出库记录-批量删除")
    //@RequiresPermissions("org.jeecg.modules:purchase_stock_out:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.purchaseStockOutService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "出库记录-通过id查询")
	@ApiOperation(value="出库记录-通过id查询", notes="出库记录-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<PurchaseStockOut> queryById(@RequestParam(name="id",required=true) String id) {
		PurchaseStockOut purchaseStockOut = purchaseStockOutService.getById(id);
		if(purchaseStockOut==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(purchaseStockOut);

	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "出库物品-通过主表ID查询")
	@ApiOperation(value="出库物品-通过主表ID查询", notes="出库物品-通过主表ID查询")
	@GetMapping(value = "/queryPurchaseStockOutGoodsByMainId")
	public Result<IPage<PurchaseStockOutGoods>> queryPurchaseStockOutGoodsListByMainId(@RequestParam(name="id",required=true) String id) {
		List<PurchaseStockOutGoods> purchaseStockOutGoodsList = purchaseStockOutGoodsService.selectByMainId(id);
		IPage <PurchaseStockOutGoods> page = new Page<>();
		PurchaseStockOut purchaseStockOut = purchaseStockOutService.getById(id);
		purchaseStockOutGoodsList.forEach(entity -> {
			BigDecimal totalNumber = purchaseStockService.findTotalNumber
					(entity.getCode(), entity.getGoodsCode(), entity.getUnitPrice());
			entity.setFinalNumber(totalNumber);
		});
		page.setRecords(purchaseStockOutGoodsList);
		page.setTotal(purchaseStockOutGoodsList.size());
		return Result.OK(page);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param purchaseStockOut
    */
    //@RequiresPermissions("org.jeecg.modules:purchase_stock_out:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, PurchaseStockOut purchaseStockOut) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<PurchaseStockOut> queryWrapper = QueryGenerator.initQueryWrapper(purchaseStockOut, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

     //配置选中数据查询条件
      String selections = request.getParameter("selections");
      if(oConvertUtils.isNotEmpty(selections)) {
           List<String> selectionList = Arrays.asList(selections.split(","));
           queryWrapper.in("id",selectionList);
      }
      //Step.2 获取导出数据
      List<PurchaseStockOut>  purchaseStockOutList = purchaseStockOutService.list(queryWrapper);

      // Step.3 组装pageList
      List<PurchaseStockOutPage> pageList = new ArrayList<PurchaseStockOutPage>();
      for (PurchaseStockOut main : purchaseStockOutList) {
          PurchaseStockOutPage vo = new PurchaseStockOutPage();
          BeanUtils.copyProperties(main, vo);
          List<PurchaseStockOutGoods> purchaseStockOutGoodsList = purchaseStockOutGoodsService.selectByMainId(main.getId());
		  purchaseStockOutGoodsList.forEach(entity -> {
			  BigDecimal totalNumber = purchaseStockService.findTotalNumber
					  (entity.getCode(), entity.getGoodsCode(), entity.getUnitPrice());
			  entity.setFinalNumber(totalNumber);
		  });
		  vo.setPurchaseStockOutGoodsList(purchaseStockOutGoodsList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "出库记录列表");
      mv.addObject(NormalExcelConstants.CLASS, PurchaseStockOutPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("出库记录数据", "导出人:"+sysUser.getRealname(), "出库记录"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("org.jeecg.modules:purchase_stock_out:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          // 获取上传文件对象
          MultipartFile file = entity.getValue();
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<PurchaseStockOutPage> list = ExcelImportUtil.importExcel(file.getInputStream(), PurchaseStockOutPage.class, params);
              for (PurchaseStockOutPage page : list) {
                  PurchaseStockOut po = new PurchaseStockOut();
				  if(StringUtils.isEmpty(page.getCode()))
				  {
					  String code = null;
					  Result result = iSysBaseAPI.executeByRuleCode("StockOutCodeRule", new JSONObject());
					  if(result.isSuccess()){
						  code = (String) result.getResult();
					  }
					  page.setCode(code);
				  }
                  BeanUtils.copyProperties(page, po);
                  purchaseStockOutService.saveMainTemp(po, page.getPurchaseStockOutGoodsList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
//              return Result.error("文件导入失败:"+e.getMessage());
			  return Result.error("文件导入失败");
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

	 /**
	  * 根据id和物品名称过滤是否有子表数据
	  * @param stockId
	  * @param goodsName
	  * @return
	  */
	 private Integer getCountByStockIdAndName(String stockId, String goodsName) {

		 return purchaseStockOutGoodsMapper.selectByStockId(stockId, goodsName);
	 }

}
